package com.example.aidocengine.validator;

import com.example.aidocengine.common.constant.BusinessConstant;
import com.example.aidocengine.common.utils.ValidationUtils;
import com.example.aidocengine.mapper.DeviceInfoMapper;
import com.example.aidocengine.mapper.PrimaryDeviceTerminologyMapper;
import com.example.aidocengine.pojo.entity.DeviceInfo;
import com.example.aidocengine.pojo.entity.PrimaryDeviceTerminology;
import com.example.aidocengine.pojo.vo.DeviceValidationVO;
import com.example.aidocengine.pojo.vo.TerminologyValidationVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

@Slf4j
@Component
public class PrimaryDeviceValidator {

    @Autowired
    private DeviceInfoMapper deviceInfoMapper;

    @Autowired
    private PrimaryDeviceTerminologyMapper primaryDeviceTerminologyMapper;

    // 缓存一次设备术语模板
    private List<PrimaryDeviceTerminology> terminologyTemplates;

    @PostConstruct
    public void initTerminologyCache() {
        refreshTerminologyCache();
    }

    /**
     * 刷新术语模板缓存
     */
    public void refreshTerminologyCache() {
        terminologyTemplates = primaryDeviceTerminologyMapper.selectAllActive();
        log.info("已加载{}个一次设备术语模板", terminologyTemplates.size());
    }

    /**
     * 校验一次设备相关的操作步骤
     */
    public TerminologyValidationVO validatePrimaryDeviceTerminology(String operationStep) {
        TerminologyValidationVO validation = new TerminologyValidationVO();
        validation.setOperationStep(operationStep);
        validation.setValidationType(BusinessConstant.VALIDATION_TYPE_PRIMARY_DEVICE);

        if (!StringUtils.hasText(operationStep)) {
            validation.setIsValid(false);
            validation.setErrorMessage("操作步骤为空");
            return validation;
        }

        // 第一步：检查操作步骤中黑色括号内容（设备双编）
        DeviceValidationVO deviceValidation = validateDeviceDoubleCode(operationStep);
        
        if (!deviceValidation.getIsValid()) {
            validation.setIsValid(false);
            validation.setErrorMessage(deviceValidation.getErrorMessage());
            return validation;
        }

        // 第二步：检查操作步骤是否符合一次设备编写原则
        boolean principleValid = validateWritingPrinciple(operationStep, deviceValidation.getDeviceCategory());
        
        if (!principleValid) {
            validation.setIsValid(false);
            validation.setErrorMessage(BusinessConstant.ERROR_WRITING_PRINCIPLE_VIOLATION);
            return validation;
        }

        validation.setIsValid(true);
        validation.setMatchedKeyword(deviceValidation.getDeviceDoubleCode());
        return validation;
    }

    /**
     * 校验设备双编是否在设备模板中存在
     */
    public DeviceValidationVO validateDeviceDoubleCode(String operationStep) {
        DeviceValidationVO validation = new DeviceValidationVO();

        // 提取括号内容
        String deviceDoubleCode = ValidationUtils.extractContentFromBrackets(operationStep);
        validation.setDeviceDoubleCode(deviceDoubleCode);

        if (!StringUtils.hasText(deviceDoubleCode)) {
            validation.setIsValid(false);
            validation.setErrorMessage("未找到设备双编（括号内容）");
            return validation;
        }

        // 在设备信息表中查找该设备双编
        DeviceInfo deviceInfo = deviceInfoMapper.selectByDeviceDoubleCode(deviceDoubleCode);
        
        if (deviceInfo == null) {
            validation.setIsValid(false);
            validation.setErrorMessage(BusinessConstant.ERROR_DEVICE_NAMING_IRREGULAR);
            log.debug("设备双编不存在于设备模板中：{}", deviceDoubleCode);
            return validation;
        }

        validation.setIsValid(true);
        validation.setDeviceCategory(deviceInfo.getDeviceCategory());
        log.debug("找到设备信息：{} -> {}", deviceDoubleCode, deviceInfo.getDeviceCategory());
        
        return validation;
    }

    /**
     * 校验操作步骤是否符合一次设备编写原则
     */
    private boolean validateWritingPrinciple(String operationStep, String deviceCategory) {
        if (terminologyTemplates == null || terminologyTemplates.isEmpty()) {
            refreshTerminologyCache();
        }

        // 根据设备分类找到对应的术语模板
        List<PrimaryDeviceTerminology> matchedTemplates = terminologyTemplates.stream()
                .filter(template -> isDeviceCategoryMatched(template.getDeviceType(), deviceCategory))
                .collect(Collectors.toList());

        if (matchedTemplates.isEmpty()) {
            // 如果没有找到特定的模板，使用通用规则
            return validateGeneralWritingPrinciple(operationStep);
        }

        // 检查是否符合任一模板的编写原则
        for (PrimaryDeviceTerminology template : matchedTemplates) {
            if (validateAgainstTemplate(operationStep, template)) {
                return true;
            }
        }

        return false;
    }

    /**
     * 检查设备分类是否匹配
     */
    private boolean isDeviceCategoryMatched(String templateDeviceType, String deviceCategory) {
        if (!StringUtils.hasText(templateDeviceType) || !StringUtils.hasText(deviceCategory)) {
            return false;
        }

        String templateLower = templateDeviceType.toLowerCase();
        String categoryLower = deviceCategory.toLowerCase();

        // 直接匹配
        if (templateLower.equals(categoryLower)) {
            return true;
        }

        // 包含匹配
        if (templateLower.contains(categoryLower) || categoryLower.contains(templateLower)) {
            return true;
        }

        // 特殊匹配规则
        if ((templateLower.contains("线路") && categoryLower.contains("线路")) ||
            (templateLower.contains("主变") && categoryLower.contains("主变")) ||
            (templateLower.contains("母线") && categoryLower.contains("母线")) ||
            (templateLower.contains("变压器") && categoryLower.contains("主变"))) {
            return true;
        }

        return false;
    }

    /**
     * 根据模板验证操作步骤
     */
    private boolean validateAgainstTemplate(String operationStep, PrimaryDeviceTerminology template) {
        String writingPrinciple = template.getWritingPrinciple();
        
        if (!StringUtils.hasText(writingPrinciple)) {
            return true; // 如果没有编写原则，则认为通过
        }

        // 这里可以根据实际的编写原则进行更复杂的验证
        // 目前使用简单的关键词匹配
        String[] principleKeywords = extractPrincipleKeywords(writingPrinciple);
        
        String operationStepLower = operationStep.toLowerCase();
        for (String keyword : principleKeywords) {
            if (StringUtils.hasText(keyword) && operationStepLower.contains(keyword.toLowerCase())) {
                return true;
            }
        }

        return false;
    }

    /**
     * 提取编写原则中的关键词
     */
    private String[] extractPrincipleKeywords(String writingPrinciple) {
        // 简单的关键词提取，可以根据实际需要进行改进
        String[] commonKeywords = {
            "投入", "退出", "切换", "操作", "分闸", "合闸", "断开", "闭合",
            "运行", "停止", "启动", "关闭", "检查", "确认", "调整", "设置"
        };
        
        return commonKeywords;
    }

    /**
     * 通用编写原则验证（当没有特定模板时使用）
     */
    private boolean validateGeneralWritingPrinciple(String operationStep) {
        // 通用验证规则：
        // 1. 包含动作词
        String[] actionWords = {
            "投入", "退出", "切换", "操作", "分闸", "合闸", "断开", "闭合",
            "运行", "停止", "启动", "关闭", "检查", "确认", "调整", "设置",
            "接通", "断开", "投运", "停运"
        };

        String operationStepLower = operationStep.toLowerCase();
        for (String actionWord : actionWords) {
            if (operationStepLower.contains(actionWord)) {
                return true;
            }
        }

        // 2. 符合设备操作的基本格式
        // 例如：将XX设备YY、XX设备从YY状态调整到ZZ状态等
        Pattern deviceOperationPattern = Pattern.compile(".*将.*设备.*|.*设备.*从.*到.*|.*设备.*状态.*");
        if (deviceOperationPattern.matcher(operationStep).find()) {
            return true;
        }

        return false;
    }
}